<template>
  <div>
    姓名：{{ user.name }} <br />
    地址：{{ user.address.city }} {{ user.address.dist }} {{ user.address.detail }} <br />
    习惯：{{ user.work.hobby.fav }}

    <div>
      <el-button @click="changeAll">整体切换</el-button>
      <br />
      <el-button @click="changeName">切换name</el-button>
      <el-button @click="changeAddr">切换地址</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, shallowRef, toRef, toRefs } from 'vue'

let user = ref({
  // let user = shallowRef({
  name: '张三',
  address: {
    city: '北京',
    detail: '上坡',
    dist: '朝阳',
  },
  work: {
    hobby: {
      fav: 'play',
    },
  },
})

console.log('ref-user:', user)
console.log('ref-user.value.address:', user.value.address)
console.log('ref-user.value.value.work.hobby:', user.value.work.hobby)
const changeAll = () => {
  user.value = {
    name: '张三1',
    address: {
      city: '北京1',
      detail: '上坡1',
      dist: '朝阳1',
    },
    work: {
      hobby: {
        fav: 'play1',
      },
    },
  }
}
const changeName = () => {
  user.value.name = '李四'
}
const changeAddr = () => {
  user.value.address.dist = '昌平'
  user.value.work.hobby.fav = 'study'
}
/**
 * 解构操作：
 */
// const { name, address, work: { hobby } } = user
// let { name, address } = user
let { name, address, work } = user.value
// let name = user.value.name
// let address = user.value.address
console.log('ref - 解构操作：', name, address, work, work.hobby)
setTimeout(() => {
  // name = 'ls'
  // address.city = '上海'
  // work.hobby.fav = 'play3'
  // console.log('ref-user解构后的值:', user)
}, 1000)

const { name: name2, address: address2, work: work2 } = toRefs(user.value)
console.log('ref - 解构操作2：', name2, address2, work2)

setTimeout(() => {
  // name2.value = 'ls'
  // address2.value.city = '上海'
  // work2.value.hobby.fav = 'play3'
  // console.log('ref-user解构后的值:', user)
}, 1000)

/**
 * 只有一个简单类型的话，可以使用toRef来获取响应式的。
 */
const name3 = toRef(user.value, 'name')
setTimeout(() => {
  name3.value = 'ls'

  console.log('ref-user解构后的值:', user)
}, 1000)

const getUserNameCalc = computed(() => {
  return user.value.name + '123'
})
</script>

<style scoped></style>
